#include <iostream>
#include <vector>
#include <set>
#include <cmath>
#include <fstream>
#include <algorithm>
#include <stack>

using namespace std;

struct VertInfo
{
    int level;
    int pred;
    VertInfo() : pred(-1), level(-1)
    {}
};

int log_2(int k)
{
    return log((double) k) / log(2.0);
}

void precalc(int**& a, vector<VertInfo>& vertex)
{
    int n = vertex.size();
    int depth = log_2(n);
    a = new int*[depth + 1];
    for (int i = 0; i <= depth; ++i)
    {
        a[i] = new int[n];
    }
    for (int i = 0 ; i < n; ++i)
    {
        a[0][i] = vertex[i].pred;
    }
    for (int i = 1; i <= depth; ++i)
    {
        for (int j = 0; j < n; ++j)
        {
            if (a[i-1][j] == -1) a[i][j] = -1;
            else a[i][j] = a[i-1][a[i-1][j]];
        }
    }
}

int return_pred(vector<VertInfo>& inform, int** a, int vert1, int vert2)
{
    if (inform[vert1].level < inform[vert2].level)
    {
        swap(vert1, vert2);
    }
    int n = inform.size();
    int depth = log_2(n);
    int k = depth;
    while (inform[vert2].level < inform[vert1].level)
    {
        if (a[k][vert1] != -1 && inform[a[k][vert1]].level >= inform[vert2].level)
        {
            vert1 = a[k][vert1];
        }
        --k;
    }
    if (vert1 == vert2) return vert1;
    for (int i = depth; i >= 0; --i)
    {
        if (a[i][vert1] != a[i][vert2])
        {
            vert1 = a[i][vert1];
            vert2 = a[i][vert2];
        }
    }
    return a[0][vert1];
}

int main()
{
    freopen("input.txt", "r", stdin);
    int n;
    scanf("%d", &n);
    ++n;
    vector<VertInfo> inform(n);
    inform[0].level = 0;
    for (int i = 0; i < n - 1; ++i)
    {
        int from, to;
        scanf("%d%d", &to, &from);
        inform[to].pred = from;
        inform[to].level = inform[from].level + 1;
    }
    int** result;
    precalc(result, inform);
    int m;
    scanf("%d", &m);
    for (int i = 0; i < m; ++i)
    {
        int vert1, vert2;
        scanf("%d%d", &vert1, &vert2);
        printf("%d\n", return_pred(inform, result, vert1, vert2));
    }
    for (int i = 0; i <= log_2(n); ++i)
    {
        delete[] result[i];
    }
    delete[] result;
    return 0;
}
